#include "CaputerCapData.h"


namespace Pacap {

/**
 * @brief initPcap
 * @return
 */
void CaputerCapData::initPcap(std::string networkCard, std::string filterStr)
{
    __initNetWorkCard(networkCard,filterStr);
}


/**
 * @brief CaputerCapData::setPcapLoop
 * @param callback : need user override GetNetWorkCardData
 * @return 0 sucessful -1 failed
 */
void CaputerCapData::setPcapLoop(GetCaputerHander getCaputerData)
{
   int ret = 0;
   ret = pcap_loop(pcap,-1,getCaputerData,nullptr);
   if(ret < 0)
   {
       throw ExceptPcap("pcap_loop failed");
   }
}


/**
 * @brief CaputerCapData::InitNetWorkCard
 * @return 0 sucessful -1 failed
 */
void CaputerCapData::__initNetWorkCard(std::string networkCard,std::string filterStr)
{
    char errBuf[PCAP_ERRBUF_SIZE]={0};
    int ret = 0;
    pcap = pcap_open_live(networkCard.c_str(),PCAPCAPUTERSIZE, 1, 0, errBuf);
    if(!pcap)
    {
        throw ExceptPcap(errBuf);
    }
    struct bpf_program filter;
    ret = pcap_compile(pcap,&filter,filterStr.c_str(),1,0);
    if(ret < 0)
    {
        throw ExceptPcap("pcap_compile do error");
    }
    ret = pcap_setfilter(pcap,&filter);
    if(ret < 0)
    {
        throw ExceptPcap("pcap_setfilter do error");
    }
}
/**
 * @brief CaputerCapData::ClosePcap
 * @return
 */
void CaputerCapData::closePcap()
{
    pcap_close(pcap);
}



}
